(function() {
	var ics = Iefgames_CS;
	if ($defined(ics.Comet)) {
		return ;
	}
	
	ics.Comet = function() {
		
		var uri = '/comet';
		
		var uuid = null;
		if (ics.isCs) {
			uuid = Cookie.read(ics.Cookie.csUuidCookieName);
		} else {
			uuid = Cookie.read(ics.Cookie.usUuidCookieName);
		}
		
		if (!uuid
				|| uuid.length !=32) {
			Cookie.write(ics.isCs ? ics.Cookie.csUuidCookieName : ics.Cookie.usUuidCookieName, uuid = ics.generateUuid(), ics.Cookie.Options);
		}
		
		var ajax = null;
		var start = function() {
			ajax = ics.Ajax();
			if (ajax == null) {
				return; // throw exception
			}
			
			var csUuid = null;
			if (!ics.isCs) {
				csUuid = Cookie.read(ics.Cookie.csUuidCookieName);
				if (!$chk(csUuid)
					|| csUuid.length != 32) {
					csUuid = null;
				}
			}
			
			ajax.open("POST",  uri + '?timestamp=' + $time(), true);// HTTP 请求的方式, URL, 是否异步
			ajax.onreadystatechange = stateChange;
			ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8;');		//给servert post方法取参数时使用
			ajax.setRequestHeader('Accept-Charset','utf-8;');		//给servert post方法取参数时使用
			ajax.send('uuid=' + uuid 
				+ (ics.isCs ? '&isCs=true' : !csUuid ? '' : '&csUuid=' + csUuid));	//如果是us的话，那么检查曾经是否有聊天过的cs，如果有直接把此csUuid协带到服务器
		}
		
		var stop = function() {
			ajax.onreadystatechange = null;
			ajax = null;
		}
		
		var stateChange = function() {
			if (ajax.readyState == 4
					&& ajax.status == 200) {
				if (!ajax.responseText.trim()) {
					return ;
				}
				
				JSON.decode(ajax.responseText.trim()).each(function(item) {
					if (!$chk(item.shoutName)) {
						return;
					}
					
					try {
						ics._(item.shoutName, item);
						stop();
					} catch (e) {
						var str = '';
						
						for (var key in e) {
							str += key + '=' + e[key] + '\n';
						}
//						alert(str);
					}
					
					start();
				});
			}
		}
		
		var comet = function(json) {
			if (json.csUuid == '') {
				throw Error('all cs are offline!');
			}
			
			Cookie.write(ics.Cookie.csUuidCookieName, json.csUuid, ics.Cookie.Options);
		}

		ics._$('comet', comet);
		ics._$('stopComet', stop);
		ics._$('startComet', start);
		
		if (ics.isCs) {
			window.addEvent('load', start);
		}
		return {}
	}()	
})();